<template lang="pug">
mt-table(
  v-bind="tableProps"
)
</template>

<script setup lang="ts">
import { Button, useMessage, type TableProps } from "@scmt/common-components";
import type {
  SpecimenEntity,
  SpecimenProjectEntity,
} from "@scmt/api-lis-specimen";
import { useApi } from "@scmt/core-api";
import { useRequest } from "@scmt/common-hooks";
import { useInspection } from "../conposables/inspection";
import type { InspectionResult } from "@scmt/api-lis-lis-data";

interface SpanMethodProps {
  row: any;
  column: any;
  rowIndex: number;
  columnIndex: number;
}

const $api = useApi();
const $message = useMessage();

const { getInspection, loading: loadingInspection } = useInspection();

//添加 Props属性
const props = defineProps({
  selectEquipment: {
    type: Object as PropType<SpecimenEntity>,
    default: () => {},
  },
});
const data = defineModel<SpecimenProjectEntity[]>({
  default: [],
});

const emit = defineEmits(["message-to-parent"]);

const { selectEquipment } = toRefs(props);

const {
  loading,
  request,
  data: requestData,
} = useRequest({
  project: (id: string) => {
    return $api.lis.specimen.porject.get(id);
  },
});

const formateData = computed(() => {
  const projectMap = data.value.reduce(
    (t, c) => {
      const { portfolioProjectId } = c;
      if (Object.prototype.hasOwnProperty.call(t, portfolioProjectId)) {
        t[portfolioProjectId].push(c);
      } else {
        t[portfolioProjectId] = [c];
      }

      return t;
    },
    {} as Record<
      string,
      Array<
        SpecimenProjectEntity & {
          portfolioProjectName: string;
          portfolioProjectId: string;
          price: number;
        }
      >
    >
  );

  return Object.entries(projectMap).reduce(
    (t, [k, v]) =>
      t.concat(
        {
          portfolioProjectName:
            v[0].portfolioProjectName + "(开单价格￥" + v[0].price + ")",
          __merge: true,
          baseProjectName: v[0].baseProjectName,
        },
        v
      ),
    [] as any[]
  );
});

const tableProps = computed(() => {
  const tableProps: TableProps = {
    loading: loading.value,
    data: formateData.value,
    spanMethod: arraySpanMethod,
    insertIndex: false,
    columns: [
      {
        prop: "baseProjectName",
        label: "检验项目",
        render: ({ row }) => {
          if (row.__merge) {
            return h(
              "div",
              {
                style: {
                  textAlign: "left",
                  color: "#35A000",
                },
              },
              [
                h("span", row.portfolioProjectName),
                h(Button, {
                  type: "primary",
                  size: "mini",
                  style: {
                    marginLeft: "var(--mt-margin)",
                  },
                  text: true,
                  onClick: () => {
                    row.__loading = true;
                    getInspection(selectEquipment.value)
                      .then(updateData)
                      .finally(() => {
                        row.__loading = false;
                      });
                  },
                  loading: row.__loading,
                  label: "同步结果",
                }),
              ]
            );
          } else {
            return row.baseProjectName;
          }
        },
      },
      {
        prop: "result",
        label: "结果",
        render: (params) => {
          if (params.row.category == "选择") {
            return h(resolveComponent("mt-select"), {
              modelValue: params.row.result,
              "onUpdate:modelValue": (val: string) => {
                params.row.result = val;
              },
              options:
                params.row.defaultValue?.split(";").map((item) => {
                  return {
                    label: item,
                    value: item,
                  };
                }) ?? [],
            });
          } else if (
            params.row.category == "文本" ||
            params.row.category == "数值"
          ) {
            return h(resolveComponent("mt-input"), {
              modelValue: params.row.result,
              "onUpdate:modelValue": (val: string) => {
                params.row.result = val;
              },
            });
          }
        },
      },
      {
        prop: "state",
        label: "状态",
        render: (params) => {
          if (
            params.row.result &&
            params.row.result > params.row.maximumValue
          ) {
            params.row.state = "↑";
            return h("div", "↑");
          } else if (
            params.row.result < params.row.minimumValue &&
            params.row.result
          ) {
            params.row.state = "↓";
            return h("div", "↓");
          } else if (params.row.result != params.row.re) {
            return h("div", "");
          }
        },
      },
      {
        prop: "unit",
        label: "单位",
      },
      {
        prop: "reference",
        label: "参考",
      },
    ],
    onRowClick: (row: any) => {
      emit("message-to-parent", row);
    },
    cellStyle: ({ row, column }) => {
      if (row.__merge) {
        return {
          backgroundColor: "#EAF5E5",
        };
      }
      if (column.label == "结果") {
        if (row.result && row.result > row.maximumValue) {
          return {
            backgroundColor: "#D9001B",
          };
        } else if (row.result && row.result < row.minimumValue) {
          return {
            backgroundColor: "#02A7F0",
          };
        } else if (row.result) {
          if (
            row.result != row.reference &&
            !row.maximumValue &&
            !row.minimumValue
          ) {
            return {
              backgroundColor: "#D9001B",
            };
          }
          return {
            backgroundColor: "#CBEBDB",
          };
        } else {
          return {
            backgroundColor: "#CBEBDB",
          };
        }
      }
    },
  };
  return tableProps;
});

const arraySpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}: SpanMethodProps) => {
  if (row.__merge) {
    if (columnIndex === 0) {
      return [1, tableProps.value.columns?.length ?? 0];
    } else {
      return [0, 0];
    }
  }
};
const query = (id: string) => {
  if (id) {
    request("project", {
      params: id,
      onSuccess: (res) => {
        const keys: [
          keyof SpecimenProjectEntity,
          keyof SpecimenProjectEntity
        ][] = [
          ["id", "id"],
          ["baseProjectName", "baseProjectName"],
          ["baseProjectId", "baseProjectId"],
          ["portfolioProjectName", "portfolioProjectName"],
          ["portfolioProjectId", "portfolioProjectId"],
          ["state", "state"],
          ["result", "result"],
          ["unit", "unit"],
          ["reference", "reference"],
          ["price", "price"],
          ["maximumValue", "maximumValue"],
          ["minimumValue", "minimumValue"],
          ["category", "category"],
          ["defaultValue", "defaultValue"],
          ["shortName", "shortName"],
        ];

        data.value = res.map((item) =>
          keys.reduce(
            (t, [sourceKey, targetKey]) => {
              Object.assign(t, {
                [targetKey ?? sourceKey]: item[sourceKey],
              });

              return t;
            },
            {
              result: "",
              state: "",
            } as SpecimenProjectEntity
          )
        );
      },
      onFail: () => {
        data.value = [];
      },
    });
  } else {
    data.value = [];
  }
};
watch(
  () => props.selectEquipment,
  (item) => {
    if (item && item.id) {
      query(item.id);
    } else {
      data.value = [];
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

const getCheckResult = () => {
  return data.value;
};

const updateData = (results: InspectionResult[]) => {
  if (Array.isArray(results) && results.length > 0) {
    results.forEach((result) => {
      const item = data.value.find(
        (item) => item.shortName === result.shortName
      );

      if (item) {
        item.result = result.result;
      }
    });
    $message.success("同步成功");
  } else {
    $message.warning("暂无检验结果");
  }
};

defineExpose({ query, getCheckResult });
</script>

<style lang="less" scoped>
:deep(.mt-table) {
  .el-input__wrapper {
    background-color: transparent;
    box-shadow: none;
  }
}
</style>
